import { Body, Controller, Get, HttpException, HttpStatus, Post, Req } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
// import Redis from 'ioredis'
import { JwtPass } from '@/common/decorator'
import { CaptchaTool } from '@/shared/utils/tool'
import { LoginUserDto } from './dto/user.dto'
import { UserService } from './user.service'

@ApiTags('后台/登录')
@Controller('admin/user')
export class UserController {
  private captcha = new CaptchaTool()

  constructor(private readonly userService: UserService) {}
  // @InjectRedis() private readonly redis: Redis

  /**
   * 用户登录(获取token)
   */
  @Post('login')
  @JwtPass()
  async loginUser(@Req() req: Request, @Body() data: LoginUserDto) {
    const isValid = this.captcha.verifyCaptcha(req.session, 'admin', data.code)
    if (!isValid) {
      throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST)
    }
    return await this.userService.login(data)
  }

  /**
   * 获取验证码
   */
  @Get('captcha')
  @JwtPass()
  getCaptcha(@Req() req: Request): string {
    const captcha = this.captcha.generateCaptcha()
    this.captcha.setCaptcha(req.session, 'admin', captcha.text)

    return captcha.imageBase64
  }
}
